import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getTimeStamp } from './auth'
import router from '@/router/auth'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// 定义一个token过期时间
const time = 60 * 60 * 2

// 封装一个token登录时间计算函数
const timeOut = () => ((Date.now() - getTimeStamp()) / 1000) > time// 当前时间减去token登录的时间

// 请求拦截器
service.interceptors.request.use(async config => {
  // console.log(config)
  const token = store.getters.token
  // console.log(token)
  if (token) {
    // console.log(timeOut())
    // console.log((Date.now() - getTimeStamp()) / 1000)
    if (timeOut()) { // 如果登录时间大于限制时间，则清空数据退回到登录页面
      await store.dispatch('user/logout')
      router.push('/login')
      return Promise.reject(new Error('身份认证已过期'))
    }
    config.headers.Authorization = 'Bearer ' + token
  }
  return config
}, err => {
  return Promise.reject(new Error(err))
}
)

// 响应拦截器
service.interceptors.response.use(res => {
  // console.log(res)
  const { data, message, success } = res.data
  if (success) {
    // Message.success(message)
    return data
  } else {
    Message.error(message)
    return Promise.reject(new Error(message))
  }
}, async function (err) {
  // console.dir(err)
  if (err.response && err.response.data && err.response.data.code === 10002) {
    await store.dispatch('user/logout')
    router.push('/login')
  }
  Message.error(err.message)
  return Promise.reject(new Error(err))
})

export default service
